package com.lql.lqlreader

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Process
import android.util.Log
import com.lql.lqlreader.service.ServiceFactory
import com.tencent.bugly.Bugly
import com.tencent.mmkv.MMKV
import timber.log.Timber
import java.lang.ref.WeakReference

/**
 * ClassName: LQlReaderApplication
 * Description: initialize the parameters in AndroidManifest.xml
 */
class LQlReaderApplication : Application() {

    // 获得全局Context
    companion object {
        @SuppressWarnings("StaticFieldLeak")
        lateinit var myContext: Context
        lateinit var myInstance: Application

        @SuppressLint("BinaryOperationInTimber")
        fun showLogoInLog() {
            Timber.tag("LQlReaderApplication ")
            Timber.d("Welcome to lQlReader ~~~\n" +
                    "      _____________\n" +
                    "     /  / _____ \\  \\\n" +
                    "    /  / /     \\ \\  \\\n" +
                    "   /  / /   __  \\ \\  \\\n" +
                    "  /  /\\ \\   \\ \\ / /\\  \\\n" +
                    " /  /__\\ \\___\\ V /__\\  \\_____\n" +
                    "/_______\\____________\\_______\\")
        }

        // 自定义Tree，设置Timber日志记录策略
        class CrashReportingTree: Timber.Tree() {
            override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
                if (BuildConfig.DEBUG || Log.isLoggable("MyTag", Log.DEBUG)) {
                    super.log(priority, message, t)
                }
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        myContext = applicationContext
        myInstance = this

        val rootDir = MMKV.initialize(this) // 初始化MMKV
        initTimber() // 轻量级Log库
        Timber.d("mmkv_root: [ $rootDir ]")
        lateInit()

        initServiceFactory()
    }

    private fun lateInit() {
        Thread {
            // 设置进程的优先级，不与主线程抢占资源
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
            initBugly() // 初始化腾讯bugly
        }.start()
    }

    private fun initServiceFactory() {
        ServiceFactory.DEFAULT_CONTEXT = WeakReference(this)
    }

    private fun initTimber() {
        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        } else {
            Timber.plant(CrashReportingTree())
        }
    }

    // 腾讯在线升级方案，Bugly库
    private fun initBugly() {
        Bugly.init(this, "8f4e37e626", false)
    }
}